package com.gin.no_gay_alliance.fragment.config;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import androidx.annotation.NonNull;

import com.gin.nga.callback.NgaCallback;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.adpter.ReleaseAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.databinding.FragmentConfigUpgradeBinding;
import com.gin.no_gay_alliance.fragment.base.BaseBindingFragment;
import com.gin.no_gay_alliance.manager.provider.VersionProvider;
import com.gin.no_gay_alliance.viewmodel.AppRelease;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;

/**
 * 管理 - 版本
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/11 00:30
 **/
public class ConfigUpgradeFragment extends BaseBindingFragment<FragmentConfigUpgradeBinding> implements NgaCallback<ArrayList<AppRelease>> {
    private ReleaseAdapter adapter;

    /**
     * onCreateView 的后续操作
     */
    @Override
    protected void onCreateView() {
        adapter = new ReleaseAdapter(requireContext());
        b.recyclerView.setAdapter(adapter);
        b.tvVersion.setText(String.format("当前版本: %s, 以下为近期版本, 点击可下载", MyApplication.getVersionName()));
        b.swipeRefreshLayout.setOnRefreshListener(this::refresh);
    }

    /**
     * 创建选项菜单
     *
     * @param menu     菜单
     * @param inflater 渲染器
     */
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.refresh_menu, menu);
    }

    /**
     * 点击选项按钮的操作
     *
     * @param item 选中的按钮
     * @return 是否消耗
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_item_refresh) {
            refresh();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onResume() {
        super.onResume();
        sendRequest(false);
    }

    /**
     * 请求成功回调
     *
     * @param data 数据
     */
    @Override
    public void onSuccess(ArrayList<AppRelease> data) {
        ui(() -> {
            adapter.updateData(data);
            onRequestFinally();
        });
    }

    /**
     * 请求之前执行的操作
     */
    @Override
    public void beforeRequest() {
        ui(() -> b.swipeRefreshLayout.setRefreshing(true));
    }

    /**
     * 请求失败回调(一般为网络访问错误)
     *
     * @param call call
     * @param e    错误
     */
    @Override
    public void onFailure(@NonNull Call call, @NonNull IOException e) {
        onRequestFinally();
    }

    private void onRequestFinally() {
        ui(() -> b.swipeRefreshLayout.setRefreshing(false));
    }

    /**
     * 刷新
     */
    private void refresh() {
        sendRequest(true);
    }

    private void sendRequest(boolean ignoreCache) {
        new VersionProvider(1, 10).async(ignoreCache, this);
    }
}
